# coding=utf8
import hashlib
import os

import time
from urllib.parse import unquote
import base64
import requests
from io import BytesIO


def get_root_path(sub='/'):
    path = os.path.split(os.path.realpath(__file__))[0]
    return os.path.realpath(path + '/../' + sub) + '/'


def str_to_time(str, format="%Y-%m-%d %H:%M:%S"):
    time_arr = time.strptime(str, format)
    return int(time.mktime(time_arr))


def time_to_str(format, unixtime=time.time()):
    time_arr = time.localtime(unixtime)
    return time.strftime(format, time_arr)


def stream_to_params(data):
    params_list = data.split('&')
    params = dict()
    tmp_list = {}
    for item in params_list:
        # chagne + to ' '
        item = item.replace('+', ' ')
        key, value = item.split('=')
        key = unquote(key)
        value = unquote(value)
        if '[]' in key:
            key = key.replace('[]', '')
            if key not in tmp_list:
                tmp_list[key] = []
            tmp_list[key].append(value)
            continue
        params[key] = value
    if tmp_list:
        for key, value in tmp_list.items():
            params.update({
                key: value
            })
    return params


# 这个暂时弃用了
def base64_img(img_url, src=True):
    img = requests.get(img_url)
    encoded = base64.b64encode(img.content)
    if src:
        extion = img.headers['Content-Type']
        encoded = 'data:' + extion + ';base64,' + encoded.decode()
    return encoded


def content_to_imme(content, ext=True):
    change_dict = {
        'image/jpeg': 'jpg',
        'image/png': 'png',
        'image/gif': 'gif',
        'images/webp': 'webp',
        'video/mp4': 'mp4'
    }
    if content in change_dict:
        imme = change_dict[content]
        if ext:
            imme = '.' + imme
        return imme
    raise ValueError("Invalid Content in table")


def imme_to_content(imme):
    change_dict = {
        'jpg': 'image/jpeg',
        'jpeg': 'image/jpeg',
        'png': 'image/png',
        'gif': 'image/gif',
        'amr': 'audio/amr',
        'mp3': 'audio/mpeg',
        'mp4': 'video/mp4'
    }
    if imme in change_dict:
        return change_dict[imme]
    raise ValueError("Invalid imme in table")


def md5sum(file_name):
    """
    根据给定文件名计算文件MD5值
    :param file_name: 文件的路径
    :return: 返回文件MD5校验值
    """

    def read_chunks(fp):
        fp.seek(0)
        chunk = fp.read(8 * 1024)
        while chunk:
            yield chunk
            chunk = fp.read(8 * 1024)
        else:  # 最后要将游标放回文件开头
            fp.seek(0)

    m = hashlib.md5()
    if isinstance(file_name, str) and os.path.exists(file_name):
        with open(file_name, 'rb') as fp:
            for chunk in read_chunks(fp):
                m.update(chunk)
    elif isinstance(file_name, BytesIO):
        for chunk in read_chunks(file_name):
            m.update(chunk)
    else:
        raise ValueError('Illegal Format or path:' + str(file_name))

    return m.hexdigest()
